use anyhow::{Context, Result};
use tracing::subscriber::set_global_default;
use tracing_appender::rolling::{RollingFileAppender, Rotation};
use tracing_subscriber::filter::{EnvFilter};
use tracing_subscriber::{fmt, Registry};
use tracing_subscriber::prelude::*;
use once_cell::sync::OnceCell;
use tracing_appender::non_blocking::WorkerGuard ;

static LOG_GUARD: OnceCell<WorkerGuard> = OnceCell::new();
static LOGGER_INITIALIZED : OnceCell<()> = OnceCell::new() ;
pub fn get_log_guard() -> Option<&'static WorkerGuard> {
    LOG_GUARD.get()
}
pub fn init_logger() -> Result<()>{
    LOGGER_INITIALIZED.get_or_try_init( || -> Result<(),anyhow::Error> {
        // 日志文件路径
        let log_dir = dirs::home_dir()
            .context("无法获取用户目录")?
            .join(".ice")
            .join("log") ;

        let file_appender = RollingFileAppender::new(
            Rotation::DAILY ,
            &log_dir ,
            "ice.log" ,
        ) ;

        // 同时输出到终端和文件
        let (non_blocking , _guard) = tracing_appender::non_blocking(file_appender);
        LOG_GUARD.set(_guard).expect("存储WorkerGuard失败");

        // 从环境变量读取日志级别  默认info
        let env_filter = EnvFilter::try_from_env("ICE_LOG")
            .unwrap_or_else(|_| EnvFilter::new("info")) ;

        let subscriber = Registry::default()
            .with(env_filter)
            .with(fmt::Layer::default().with_writer(std::io::stderr) )
            .with(fmt::Layer::default()
                .with_writer(non_blocking)
                .json()
            );

        set_global_default(subscriber)
            .with_context(|| "设置全局日志 subscriber 失败".to_string())? ;
        tracing::debug!("日志系统初始化成功！日志文件路径: {}", log_dir.display());
        Ok(())
    })? ;
    Ok(())
}